package com.pubinfo.passbook.data.rabbitmq;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
import com.pubinfo.passbook.common.model.bo.rabbitmq.TbCert;
import com.pubinfo.passbook.common.model.constant.RedisKey;
import com.pubinfo.passbook.common.service.cache.JedisManage;
import com.pubinfo.passbook.common.service.master.TRabbitmqOrgService;
import com.pubinfo.passbook.common.service.master.TRabbitmqPersonService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@Slf4j
@Component
public class ReceiveService {
  @Resource
  JedisManage jedisManage;
  
  @Autowired
  TRabbitmqPersonService personService;
  
  @Autowired
  TRabbitmqOrgService orgService;
  
  /**
   * @param json    消息内容
   * @param channel 通道
   * @param message 消息主体()
   */
  
  @RabbitListener(queues = {"queues_dzpj"}, autoStartup = "false")
  public void process(String json, Channel channel, Message message) throws IOException {
    String str = new String(message.getBody());
    // log.info(str + ":------>" + str.equals(json));
    JSONObject jsonObject = JSON.parseObject(str);
    Boolean status = false;
    if (RedisKey.PERSON.equals(jsonObject.getString("type"))) {
      //保存人员到redis,方便校验用户.
      List<TbCert> tbCerts = JSON.parseArray(JSONObject.toJSONString(JSONPath.eval(jsonObject, "$.context.tbCert")), TbCert.class);
      if (CollectionUtils.isNotEmpty(tbCerts)) {
        tbCerts.forEach(cert -> {
          jedisManage.putStr(RedisKey.PERSION_KEY + cert.getCertNo(), cert.getCertName());
        });
      }
      status = personService.insertPersion(jsonObject);
    } else if (RedisKey.ORG.equals(jsonObject.getString("type"))) {
      status = orgService.insertOrg(jsonObject);
    }
    
    if (status) {
      channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    } else {
      channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);      //否认消息
    }
  }
}
